#######################################################################
#######################################################################
## Bechtel, Michael M./Hainmueller, Jens/Margalit, Yotam
## "Policy Design and Domestic Support for International Bailouts."
## First posted: October 2012
## Published version: 2019, European Journal of Political Research 56 (4): 864–886.
#######################################################################
#######################################################################

# Figure 3: The Effects of Bailout Policy Features on Voter Support
rm(list=ls())
library(foreign)
library(ggplot2)

# Set directory
resultspath <- "~/Desktop/Repdata Bailouts EJPR"

setwd(resultspath)
# function to prepare data
prepdata <- function(d){
  d$var <- rownames(d)
  colnames(d) <- c("pe","se","var")
  d$order <- 1:nrow(d)
  # compute Cis
  d$se <- sqrt(d$se)
  d$upper <-d$pe + 1.96*d$se
  d$lower <-d$pe - 1.96*d$se
  
  # define group
  d$group <- NA
  d$group[d$var %in% paste(c("1b",2:4),".FeatTargetCountry",sep="")]         <- "Country"
  d$group[d$var %in% paste(c("1b",2:6),".FeatConditions",sep="")]           <- "Conditions"
  d$group[d$var %in% paste(c("19b",21,27,53),".FeatGershare",sep="")]         <- "Share"
  d$group[d$var %in% paste(c("123b",189,211,418),".FeatGercontrib",sep="")]       <- "Contribution"
  d$group[d$var %in% paste(c("10b",20,50,75),".FeatHaircut",sep="")]          <- "Haircut"
  d$group[d$var %in% paste(c("1b",2:6),".FeatEndors",sep="")]        <- "Endorser"
  # exclude irrelevant vars
  d<-   d[is.na(d$group)==F,]
  # label attributes
  offset <- c("   ")
  d$var[d$group=="Country"] <- paste(offset,c("Spain","Ireland","Italy","Greece"))
  d$var[d$group=="Conditions"] <- paste(offset,c("5% spending cut","15% spending cut", "35% spending cut",
                                                 "5% public jobs cut","15% public jobs cut","35% public jobs cut"))
  d$var[d$group=="Share"] <- paste(offset,c("19%","21%","27%","53%"))
  d$var[d$group=="Contribution"] <- paste(offset,c("123 bn Eur","189 bn Eur","211 bn Eur","418 bn Eur"))
  d$var[d$group=="Haircut"] <- paste(offset,c("10%","20%","50%","75%"))
  d$var[d$group=="Endorser"] <- paste(offset,c("Government","Bundesbank","European Central Bank","Opposition",
                                               "Council of Economic Advisors","International Monetary Fund"))
  
  d <- d[order(d$order),]
  dd <- data.frame(var= c("Country Receiving Bailout:",
                          " ",
                          "Conditions for Receiving Country:",
                          "  ",
                          "Germany's Share of Bailout:",
                          "   ",
                          "Germany's Contribution to Bailout:",
                          "    ",
                          "Haircut for Private Investors:",
                          "     ",
                          "Endorser of Bailout Proposal:"
  ),order=c(.5,4.1,4.5,10.1,10.5,14.1,14.5,18.1,18.5,22.1,22.5),
  pe=1,se=1,upper=1,lower=1,group=NA)
  d <- rbind(d,dd)
  d <-d[order(d$order),]
  
  d$order  <- 1:nrow(d)
  d$resort[d$order %in% 21:26] <- 1
  d$resort[d$order %in% 15:20] <- 2
  d$resort[d$order %in% 27:32] <- 3
  d$resort[d$order %in% 7:14] <- 4
  d$resort[d$order %in% 33:39] <- 5
  d$resort[d$order %in% c(1:5)] <- 6
  d$resort[d$order %in% 6] <- 5.5
  d <- d[order(d$resort),]
  d$var <- factor(d$var,levels=unique(d$var)[length(d$var):1])
  d$gruppe <- factor(d$group,levels=unique(d$group))
  return(d)
}

model <- c("fig3.txt")
modelname <- c("Change in Pr(Vote Against Bailout)")
d <- read.table(model)
d <- prepdata(d)


llabels <- c("-.3","-.2","-.1","0",".1",".2",".3",".4")
yylab <- modelname

p = ggplot(d,aes(y=pe,x=var))
p = p + coord_flip(ylim = c(-.1, .2))
p = p + geom_hline(yintercept = 0,size=.25,colour="gray15",linetype="solid") 
p = p + geom_pointrange(aes(ymin=lower,ymax=upper),size=.6)
p = p + scale_y_continuous(name=yylab,breaks=seq(-.3,.4,.1),labels=llabels)
p = p + scale_colour_grey("Attribute:") + scale_x_discrete(name="")
print(p)

theme_bw1 <- function(base_size = 13, base_family = "") {
  theme_grey(base_size = base_size, base_family = base_family) %+replace%
    theme(
      axis.text.x =       element_text(size = base_size, colour = "black",  hjust = .5 , vjust=1),
      axis.text.y =       element_text(size = base_size , colour = "black", hjust = 0 , vjust=.5 ), # changes position of X axis text
      axis.ticks =        element_line(colour = "grey50"),
      axis.title.y =      element_text(size = base_size,angle=90,vjust=.01,hjust=.1),
      legend.position = "none"
    )
}

dev.off()

pdf(paste("fig3",".pdf",sep=""),width=13,height=8)
p = p  + theme_bw1()
print(p)
dev.off()

ggsave("fig3.tiff",p,width=13,height=8)
ggsave("fig3.jpeg",p,width=13,height=8)

write.csv(d[,c("pe","se","var","upper","lower","group")],
          file=paste(model,".csv",sep=""))




#################################################################
# Figure A2 (7 point scale): The Effects of Bailout Policy Features on Voter Support
model <- c("figA2.txt")
modelname <- c("Change in Opposition to Bailout (1-7 Scale)")
d <- read.table(model)
d <- prepdata(d)


llabels <- c("-.3","-.2","-.1","0",".1",".2",".3",".4",".5",".6")
yylab <- modelname

p = ggplot(d,aes(y=pe,x=var))
p = p + coord_flip(ylim = c(-.3, .65))
p = p + geom_hline(yintercept = 0,size=.25,colour="gray15",linetype="solid") 
p = p + geom_pointrange(aes(ymin=lower,ymax=upper),size=.6)
p = p + scale_y_continuous(name=yylab,breaks=seq(-.3,.6,.1),labels=llabels)
p = p + scale_colour_discrete("Attribute:") + scale_x_discrete(name="")
print(p)

theme_bw1 <- function(base_size = 13, base_family = "") {
  # Starts with theme_grey and then modify some parts
  theme_grey(base_size = base_size, base_family = base_family) %+replace%
    theme(
      axis.text.x =       element_text(size = base_size, colour = "black",  hjust = .5 , vjust=1),
      axis.text.y =       element_text(size = base_size , colour = "black", hjust = 0 , vjust=.5 ), # changes position of X axis text
      axis.ticks =        element_line(colour = "grey50"),
      axis.title.y =      element_text(size = base_size,angle=90,vjust=.01,hjust=.1),
      legend.position = "none"
    )
}

dev.off()

pdf(paste("figA2",".pdf",sep=""),width=13,height=8)
p = p  + theme_bw1()
print(p)
dev.off()
write.csv(d[,c("pe","se","var","upper","lower","group")],
          file=paste(model,".csv",sep=""))

ggsave("figA2.tiff",p,width=13,height=8)
ggsave("figA2.jpeg",p,width=13,height=8)


#################################################################
# Figure A3 (Binary Prefer): The Effects of Bailout Policy Features on Voter Support
model <- c("figA3.txt")
modelname <- c("Change in Pr(Oppose Bailout) - Forced Choice")
d <- read.table(model)
d <- prepdata(d)

llabels <- c("-.3","-.2","-.1","0",".1",".2",".3",".4")
yylab <- modelname

p = ggplot(d,aes(y=pe,x=var))
p = p + coord_flip(ylim = c(-.1, .4))
p = p + geom_hline(yintercept = 0,size=.25,colour="gray15",linetype="solid") 
p = p + geom_pointrange(aes(ymin=lower,ymax=upper),size=.6)
p = p + scale_y_continuous(name=yylab,breaks=seq(-.3,.4,.1),labels=llabels)
p = p + scale_colour_discrete("Attribute:") + scale_x_discrete(name="")
print(p)

dev.off()
pdf(paste("figA3",".pdf",sep=""),width=13,height=8)
p = p  + theme_bw1()
print(p)
dev.off()
write.csv(d[,c("pe","se","var","upper","lower","group")],
          file=paste(model,".csv",sep=""))

ggsave("figA3.tiff",p,width=13,height=8)
ggsave("figA3.jpeg",p,width=13,height=8)


####################################################################
####################################################################
## test for subsets

# Figure 4: The Effects of Bailouts Policy Features on Voter Support, by Income Groups
# Figure 5: The Effects of Bailout Policy Features on Voter Support by Ideology
# Figure 6: The Effects of Bailout Policy Features on Voter Support by Education
# Figure A1: The Effects of Bailout Policy Features on Voter Support by Stock Ownership
# Figure A.4: Effect of Bailout Policy Features on Voter Support for Bailout by Contest

# list of subsets
llabels <- c("-.3","-.2","-.1","0",".1",".2",".3",".4")
yylab <- c("Change in Pr(Vote Against Bailout)")

dl <- list()

dl[[1]] <- list(subfilename="hhinc",
                subsetnlabel="",
                slevels=1:2,
                slabels=c("Household Income: Low",
                          "Household Income: High"))

dl[[2]] <- list(subfilename="ideo",
                subsetnlabel="",
                slevels=1:2,
                slabels=c("Ideology: Left",
                          "Ideology: Right"))

dl[[3]] <- list(subfilename="educ",
                subsetnlabel="",
                slevels=1:2,
                slabels=c("Education: Low",
                          "Education: High"))

dl[[4]] <- list(subfilename="task",
                subsetnlabel="",
                slevels=1:4,
                slabels=c("Choice Task: 1",
                          "Choice Task: 2",
                          "Choice Task: 3",
                          "Choice Task: 4"))

dl[[5]] <- list(subfilename="ownstocks",
                subsetnlabel="",
                slevels=1:2,
                slabels=c("Own Stock: No",
                          "Own Stock: Yes"))

# do the plots
try(dev.off())
for(kk in 1:length(dl)){
  filenames <- paste(paste(dl[[kk]]$subfilename,
                           dl[[kk]]$slevels,sep=""),
                     ".txt",sep="")
  
  alldata <- list()
  for(i in 1:length(filenames)){
    d <- read.table(filenames[i])
    alldata[[i]] <- prepdata(d)
    alldata[[i]]$subset      <- dl[[kk]]$slevels[i]
    alldata[[i]]$subsetlabel <- paste(dl[[kk]]$subsetnlabel,
                                      dl[[kk]]$slabels[i],sep=" ")
  }
  
  d <- alldata[[1]]
  for(i in 2:length(filenames)){
    d <- rbind(d,alldata[[i]])
  }
  
  d$subsetlabel <- factor(d$subsetlabel,levels=unique(d$subsetlabel))
  
  p = ggplot(d ,aes(y=pe,x=var))
  p = p + facet_grid(.~subsetlabel)
  p = p + coord_flip(ylim = c(-.1, .25))
  p = p + geom_hline(yintercept = 0,size=.25,colour="gray15",linetype="solid") 
  p = p +geom_pointrange(aes(ymin=lower,ymax=upper),size=.6)
  p = p + scale_y_continuous(name=yylab,breaks=seq(-.3,.4,.1),labels=llabels)
  p = p + scale_colour_discrete("Attribute:") + scale_x_discrete(name="")
  p = p + theme_bw1()
  print(p)
  
  dev.off()
  pdf(paste("1",dl[[kk]]$subfilename,".pdf",sep=""),width=14,height=10)
  print(p)
  dev.off()
  
  ggsave(paste("1",dl[[kk]]$subfilename,".tiff",sep=""),p,width=14,height=10)
  ggsave(paste("1",dl[[kk]]$subfilename,".jpeg",sep=""),p,width=14,height=10)
  
  
  write.csv(d[,c("pe","se","var","upper","lower","group","subset","subsetlabel")],
            file=paste("1",dl[[kk]]$subfilename,".csv",sep=""))
  
}

########################
#  Figure A.5: Effect of Bailout Policy Features on Voter Support for Bailout by Receiving Country

llabels <- c("-.3","-.2","-.1","0",".1",".2",".3",".4")
yylab <- c("Change in Pr(Vote Against Bailout)")

# function to prepare data for by country
prepdata2 <- function(d){
  d$var <- rownames(d)
  colnames(d) <- c("pe","se","var")
  d$order <- 1:nrow(d)
  # compute Cis
  d$se <- sqrt(d$se)
  d$upper <-d$pe + 1.96*d$se
  d$lower <-d$pe - 1.96*d$se
  
  # define group
  d$group <- NA
  d$group[d$var %in% paste(c("1b",2:6),".FeatConditions",sep="")]           <- "Conditions"
  d$group[d$var %in% paste(c("19b",21,27,53),".FeatGershare",sep="")]         <- "Share"
  d$group[d$var %in% paste(c("123b",189,211,418),".FeatGercontrib",sep="")]       <- "Contribution"
  d$group[d$var %in% paste(c("10b",20,50,75),".FeatHaircut",sep="")]          <- "Haircut"
  d$group[d$var %in% paste(c("1b",2:6),".FeatEndors",sep="")]        <- "Endorser"
  # exclude irrelevant vars
  d<-   d[is.na(d$group)==F,]
  # label attributes
  offset <- c("   ")
  d$var[d$group=="Conditions"] <- paste(offset,c("5% spending cut","15% spending cut", "35% spending cut",
                                                 "5% public jobs cut","15% public jobs cut","35% public jobs cut"))
  d$var[d$group=="Share"] <- paste(offset,c("19%","21%","27%","53%"))
  d$var[d$group=="Contribution"] <- paste(offset,c("123 bn Eur","189 bn Eur","211 bn Eur","418 bn Eur"))
  d$var[d$group=="Haircut"] <- paste(offset,c("10%","20%","50%","75%"))
  d$var[d$group=="Endorser"] <- paste(offset,c("Government","Bundesbank","European Central Bank","Opposition",
                                               "Council of Economic Advisors","International Monetary Fund"))
  
  d <- d[order(d$order),]
  dd <- data.frame(var= c("Conditions for Receiving Country:",
                          "  ",
                          "Germany's Share of Bailout:",
                          "   ",
                          "Germany's Contribution to Bailout:",
                          "    ",
                          "Haircut for Private Investors:",
                          "     ",
                          "Endorser of Bailout Proposal:"
  ),order=c(4.5,10.1,10.5,14.1,14.5,18.1,18.5,22.1,22.5)-4,
  pe=1,se=1,upper=1,lower=1,group=NA)
  d <- rbind(d,dd)
  d <-d[order(d$order),]
  
  d$order  <- 1:nrow(d)
  d$resort <- NA
  d$resort[d$order %in% ((21:26)-6)] <- 1
  d$resort[d$order %in% ((15:20)-6)] <- 2
  d$resort[d$order %in% ((27:32)-6)] <- 3
  d$resort[d$order %in% ((7:14)-6)] <- 4
  d$resort[d$order %in% ((33:39)-6)] <- 5
  d <- d[order(d$resort),]
  d$var <- factor(d$var,levels=unique(d$var)[length(d$var):1])
  d$gruppe <- factor(d$group,levels=unique(d$group))
  return(d)
}

dl <- list()
dl[[1]] <- list(subfilename="country",
                subsetnlabel="",
                slevels=1:4,
                slabels=c("Receiver: Spain",
                          "Receiver: Ireland",
                          "Receiver: Italy",
                          "Receiver: Greece"))

# do the plots
try(dev.off())
for(kk in 1:length(dl)){

  filenames <- paste(paste(dl[[kk]]$subfilename,
                           dl[[kk]]$slevels,sep=""),
                     ".txt",sep="")
  
  alldata <- list()
  for(i in 1:length(filenames)){
    d <- read.table(filenames[i])
    alldata[[i]] <- prepdata2(d)
    alldata[[i]]$subset      <- dl[[kk]]$slevels[i]
    alldata[[i]]$subsetlabel <- paste(dl[[kk]]$subsetnlabel,
                                      dl[[kk]]$slabels[i],sep=" ")
  }
  
  d <- alldata[[1]]
  for(i in 2:length(filenames)){
    d <- rbind(d,alldata[[i]])
  }
  
  d$subsetlabel <- factor(d$subsetlabel,levels=unique(d$subsetlabel))
  
  p = ggplot(d ,aes(y=pe,x=var))
  p = p + facet_grid(.~subsetlabel)
  p = p + coord_flip(ylim = c(-.1, .25))
  p = p + geom_hline(yintercept = 0,size=.25,colour="gray14",linetype="solid") 
  p = p +geom_pointrange(aes(ymin=lower,ymax=upper),size=.6)
  p = p + scale_y_continuous(name=yylab,breaks=seq(-.3,.4,.1),labels=llabels)
  p = p + scale_colour_discrete("Attribute:") + scale_x_discrete(name="")
  p = p + theme_bw1()
  print(p)

  dev.off()
  pdf(paste("1",dl[[kk]]$subfilename,".pdf",sep=""),width=14,height=10)
  print(p)
  dev.off()
  
  ggsave(paste("1",dl[[kk]]$subfilename,".tiff",sep=""),p,width=14,height=10)
  ggsave(paste("1",dl[[kk]]$subfilename,".jpeg",sep=""),p,width=14,height=10)
  
  
  write.csv(d[,c("pe","se","var","upper","lower","group","subset","subsetlabel")],
            file=paste("1",dl[[kk]]$subfilename,".csv",sep=""))
  
}



########################
# Figure 7: Predicted Voter Support for Various Bailout Packages

rm(list=ls())
library(foreign)

# function to get labels
getlabels <- function(vector){
  
  label <- c("")
  for(i in c(4,3,5,2,6,1)){
    
    if(i==4){ # FeatGercontrib
      lab <- paste("Germany's Contribution: ",vector[i],"bn Eur",sep="")
      label = paste(label,lab,sep="")
    } 
    
    if(i==3){ # FeatGershare
      lab <- paste("Germany's Share: ",vector[i],"%",sep="")
      label = paste(label,lab,sep="; ")
    }
    
    if(i==5){ # FeatHaircut
      lab <- paste("Haircut: ",vector[i],"%",sep="")
      label = paste(label,lab,sep="; ")
    }
    
    if(i==2){ # FeatConditions
      if(vector[i]==1){lab <- c("5% spending cut")}
      if(vector[i]==2){lab <- c("15% spending cut")}
      if(vector[i]==3){lab <- c("35% spending cut")}
      if(vector[i]==4){lab <- c("5% public jobs cut")}
      if(vector[i]==5){lab <- c("15% public jobs cut")}
      if(vector[i]==6){lab <- c("35% public jobs cut")}
      lab <- paste("Condition: ",lab,sep="")
      label = paste(label,lab,sep="; ")
    }
    
    if(i==6){ # FeatEndors
      if(vector[i]==1){lab <- c("Government")}
      if(vector[i]==2){lab <- c("Bundesbank")}
      if(vector[i]==3){lab <- c("European Central Bank")}
      if(vector[i]==4){lab <- c("Opposition")}
      if(vector[i]==5){lab <- c("Council of Economic Advisors")}
      if(vector[i]==6){lab <- c("International Monetary Fund")}
      lab <- paste("Endorser: ",lab,sep="")
      label = paste(label,lab,sep="; ")
    }
    
    if(i==1){ # Target Country
      if(vector[i]==1){lab <- c("Spain")}
      if(vector[i]==2){lab <- c("Ireland")}
      if(vector[i]==3){lab <- c("Italy")}
      if(vector[i]==4){lab <- c("Greece")}
      lab <- paste("Receiver: ",lab,sep="")
      label = paste(label,lab,sep="; ")
    }
    
  }
  return(label) 
}

d <- read.table("policy2.txt")

d$ub <- d$pe+1.96*d$se
d$lb <- d$pe-1.96*d$se

d$labels <- NA
for(i in 1:nrow(d)){
  d$labels[i] <- getlabels(d[i,colnames(d)[3:8]])
}

#d <- d[-3,]
d$index <- 1:nrow(d)

try(dev.off())
#pdf("fig7.pdf",width=12,height=8)
#tiff("fig7.tiff",width = 3000, height = 2000, compression = c("none"),pointsize = 36)
jpeg("fig7.jpeg",width = 3000, height = 2000, quality=200,pointsize = 36)

plot(x=d$pe,y=d$index,
    ylim=c(0.6,max(d$index)+.6),
    xlim=c(.1,.85),
   # xlab="Voters that Support Bailout (%)                                                                  ",
     xlab="                         % Voting Against Bailout",
    ylab="",
    xaxt="n",
    yaxt="n",
    pch=19
    
     )
axis(side=2,at=d$index,labels=NA)
axis(side=1,at=seq(.3,.8,.1),labels=seq(.3,.8,.1)*100)

arrows(x0=d$lb, y0=d$index, x1=d$ub,y1=d$index,angle=90,code=3,length=.2) 
abline(v=.5,lty=3)
#abline(v=d$,lty=2)

for(i in 1:nrow(d)){
text(x=rep(.17,6),y=d$index[i]+seq(.3,-.3,length.out=6),labels=strsplit(d$labels[i],"; ")[[1]]
     ,cex=.75)
}

arrows(x0=d$lb[which(d$percentile==999)], y0=d$index[which(d$percentile==999)], x1=d$ub[which(d$percentile==999)],y1=d$index[which(d$percentile==999)]
       ,angle=90,code=3,length=.2,col="gray")
points(x=d$pe[which(d$percentile==999)], y=d$index[which(d$percentile==999)],pch=15,col="gray")

dev.off()




# Figure 8: Predicted Voter Support for Various Bailout Packages (Single Change in One Feature Only)

d <- read.table("policy_supplevls.txt")

d$ub <- d$pe+1.96*d$se
d$lb <- d$pe-1.96*d$se

d$labels <- NA
for(i in 1:nrow(d)){
  d$labels[i] <- getlabels(d[i,colnames(d)[3:8]])
}

#d <- d[-3,]
d$index <- 1:nrow(d)

try(dev.off())
#pdf("fig8.pdf",width=12,height=8)
#tiff("fig8.tiff",width = 3000, height = 2000,compression = c("none"),pointsize = 36)
jpeg("fig8.jpeg",width = 3000, height = 2000, quality=200,pointsize = 36)

plot(x=d$pe,y=d$index,
     ylim=c(0.6,max(d$index)+.6),
     xlim=c(.1,.85),
     # xlab="Voters that Support Bailout (%)                                                                  ",
     xlab="                         % Voting Against Bailout",
     ylab="",
     xaxt="n",
     yaxt="n",
     pch=19
     
)
axis(side=2,at=d$index,labels=NA)
axis(side=1,at=seq(.3,.8,.1),labels=seq(.3,.8,.1)*100)

arrows(x0=d$lb, y0=d$index, x1=d$ub,y1=d$index,angle=90,code=3,length=.2) 
abline(v=.5,lty=3)
#abline(v=d$,lty=2)

for(i in 1:nrow(d)){
  text(x=rep(.17,6),y=d$index[i]+seq(.3,-.3,length.out=6),labels=strsplit(d$labels[i],"; ")[[1]]
       ,cex=.75)
}

arrows(x0=d$lb[which(d$percentile==999)], y0=d$index[which(d$percentile==999)], x1=d$ub[which(d$percentile==999)],y1=d$index[which(d$percentile==999)]
       ,angle=90,code=3,length=.2,col="gray")
points(x=d$pe[which(d$percentile==999)], y=d$index[which(d$percentile==999)],pch=19,col="gray")

dev.off()




